package com.feng.store.controller;

import com.feng.store.controller.ex.FileEmptyException;
import com.feng.store.controller.ex.FileSizeException;
import com.feng.store.controller.ex.FileTypeException;
import com.feng.store.controller.ex.FileUploadIOException;
import com.feng.store.entity.User;
import com.feng.store.service.IUserService;
import com.feng.store.service.ex.InsertException;
import com.feng.store.service.ex.UsernameDuplicatdException;
import com.feng.store.util.JsonResult;
import org.apache.poi.EmptyFileException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


@RestController
@RequestMapping("users")
public class UserController extends BaseController{
    @Autowired
    private IUserService userService;

    /**
     * 用户的注册方法
     * @param user
     * @return
     */
    @RequestMapping("/reg")
    public JsonResult<Void> reg(User user) {
      //创建响应结果对象
        JsonResult<Void> result=new JsonResult<>();
        userService.reg(user);
        return new JsonResult<>(OK);
    }
//public class UserController {
//    @Autowired
//    private IUserService userService;
//    @RequestMapping("/reg")
//    public JsonResult<Void> reg(User user){
//      //创建响应结果对象
//        JsonResult<Void> result=new JsonResult<>();
//        try {
//            userService.reg(user);
//            result.setState(200);
//            result.setMessage("用户注册成功！");
//        } catch (UsernameDuplicatdException e) {
//            result.setState(4000);
//            result.setMessage("用户名已存在！");
//        }catch (InsertException e){
//            result.setState(5000);
//            result.setMessage("不好意思,网络出现了一点点波动~");
//        }
//        return result;
//    }

    /**
     * 用户的登录方法
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/login")
    public JsonResult<User> login(String username, String password, HttpSession session){
        User data=userService.login(username,password);
        session.setAttribute("uid",data.getUid());
        session.setAttribute("username",data.getUsername());
        //获取session中绑定的数据
        System.out.println(getuidFromSession(session));
        System.out.println(getUsernameFromSession(session));
        return new JsonResult<User>(OK,data);
    }

    /**
     * 修改用户密码
     * @param session
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @RequestMapping("change_password")
    public JsonResult<Void> changePassword(HttpSession session,String oldPassword,String newPassword){
        Integer uid = getuidFromSession(session);
        String username=getUsernameFromSession(session);
        userService.changpassword(uid,username,oldPassword,newPassword);
        return new JsonResult<>(OK);
    }

    /**
     * 通过Uid获得用户的信息
     * @param session
     * @return
     */
    @RequestMapping("/get_by_uid")
    public JsonResult<User> getByUid(HttpSession session){
        Integer uid = (Integer) session.getAttribute("uid");
        User result = userService.getByUid(uid);
        System.out.println(result);
        return new JsonResult(OK,result);
    }
    @RequestMapping("/change_info")
    public  JsonResult<Void> changeInfo(HttpSession session,User user){

      userService.changgeInfo((Integer) session.getAttribute("uid"),getUsernameFromSession(session),user);
      return new JsonResult<>(OK);
    }
    /** 设置上传文件的最大值 */
    public static final int AVATAR_MAX_SIZE=10*1024*1024;
    /** 限制上传文件的类型*/
    public static final List<String> AVATAR_TYRE=new ArrayList<>();
    static {
        AVATAR_TYRE.add("image/jpeg");
        AVATAR_TYRE.add("image/png");
        AVATAR_TYRE.add("image/bmp");
        AVATAR_TYRE.add("image/gif");

    }
    /**
     * MultipartFile接口是SpringMvc提供的一个接口，这个接口为我们包装了
     * 获取文件类型的数据（任何类型的file都可以接收）
     * @param session
     * @param file
     * @return
     */
    @RequestMapping("change_avatar")
    public JsonResult<String> changeAvatar(HttpSession session, MultipartFile file){
        if(file.isEmpty()){
            throw new FileEmptyException("文件为空");
        }
        if(file.getSize()>AVATAR_MAX_SIZE){
            throw new FileSizeException("文件超出限制");
        }
        //判断文件的类型是否是我们规定的h后缀类型
        //        String originalFilename = file.getOriginalFilename();
////        int i = originalFilename.indexOf(".");
////        String substring = originalFilename.substring(i);
        String contentType = file.getContentType();
        if(!AVATAR_TYRE.contains(contentType)){
            throw new FileTypeException("文件类型不支持");
        }
        //上传的文件.../upload/文件.png
        String parent = session.getServletContext().getRealPath("upload");
        System.out.println(parent);
        File dir=new File(parent);
        if(!dir.exists()){//检测目录是否存在
            dir.mkdir();//创建当前目录
        }
        //获取到这个文件的名称，UUID生成一个新的字符串作为文件名
        String originalFilename = file.getOriginalFilename();
        System.out.println("originalFilename="+originalFilename);

        int index=originalFilename.indexOf(".");
        String suffix= originalFilename.substring(index);
        String filename = UUID.randomUUID().toString().toUpperCase()+suffix;

        //先在指定的目录下创建一个同名字的空文件
        File dest=new File(dir,filename);//是一个空文件
        //参数file中数据写入到这个空文件中
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            throw new FileUploadIOException("文件读写异常");
        }
        Integer uid= (Integer) session.getAttribute("uid");
        String username = (String) session.getAttribute("username");
        String avatar="/upload/"+filename;
        userService.changgeAvatar(avatar,uid,username);
        //返回用户头像的路径给前端页面，将来用于头像展示使用
        return new JsonResult<>(OK,avatar);


    }
}
